import { scheduleUpdateOnFiber } from "./ReactFiberWorkloop";

let currentlyRenderingFiber = null;
let workInProgressHook = null;

export function renderWithHooks(wip) {
  currentlyRenderingFiber = wip;
  currentlyRenderingFiber.memorizedState = null;
  workInProgressHook = null;
}

function updateWorkInProgressHook() {
  let hook;
  let current = currentlyRenderingFiber.alternate;
  if (current) {
    // 更新阶段
    currentlyRenderingFiber.memorizedState = current.memorizedState;

    if (workInProgressHook) {
      hook = workInProgressHook = workInProgressHook.next;
    } else {
      // head hook
      hook = workInProgressHook = current.memorizedState;
    }
  } else {
    //   初次渲染
    hook = {
      memorizedState: null, // 状态值
      next: null, // 下一个hook
    };
    if (workInProgressHook) {
      workInProgressHook.next = hook;
      workInProgressHook = hook
    } else {
      // head hook
      currentlyRenderingFiber.memorizedState = hook;
      workInProgressHook = hook
    }
  }
  return hook;
}

// hook = {
//     memorizedState: null// 状态值
//     next: null// 下一个hook
// }
export function useReducer(reducer, initalState) {
  const hook = updateWorkInProgressHook();

  console.log('reducer', hook)

  if (!currentlyRenderingFiber.alternate) {
    //   初次渲染
    hook.memorizedState = initalState;
  }
  const dispatch = () => {
    hook.memorizedState = reducer(hook.memorizedState);
    scheduleUpdateOnFiber(currentlyRenderingFiber);
  };
  return [hook.memorizedState, dispatch];
}
